﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Shohdi.DataHandler;
using DatabaseComponent;

public partial class CatalogPageAR : System.Web.UI.Page
{

    public string strOrder
    {
        get
        {
            if (ViewState["strOrder"] == null)
            {
                ViewState["strOrder"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["strOrder"].ToString()] == null)
            {
                Session[ViewState["strOrder"].ToString()] = "";

            }

            return (string)Session[ViewState["strOrder"].ToString()];

        }
        set
        {
            if (ViewState["strOrder"] == null)
            {
                ViewState["strOrder"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["strOrder"].ToString()] = value;
        }
    }

    public List<Courses> lstGridCourses
    {
        get
        {
            if (ViewState["lstGridCourses"] == null)
            {
                ViewState["lstGridCourses"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["lstGridCourses"].ToString()] == null)
            {
                Session[ViewState["lstGridCourses"].ToString()] = new List<Courses>();

            }

            return (List<Courses>)Session[ViewState["lstGridCourses"].ToString()];

        }
        set
        {
            if (ViewState["lstGridCourses"] == null)
            {
                ViewState["lstGridCourses"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["lstGridCourses"].ToString()] = value;
        }



    }


    



    /// <summary>
    /// it will check the security and customize the page
    /// </summary>
    /// <param name="currentPerson">the person to set security to his previleges</param>
    protected void checkSecurityAndCustomizePage(Persons currentPerson)
    {
        //Security Check

        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Catalog_Page))
            Response.Redirect("LoginAR.aspx");



       





    }





   


    


   



    


   


   





    protected void Page_Load(object sender, EventArgs e)
    {


        Persons currentPerson = GlobalVars.getCurrentPersonAR();




        if (!Page.IsPostBack)
        {
            
            checkSecurityAndCustomizePage(currentPerson);


            bindddlLanguage();
            showLanguage();

            BindGrid();


            if (Request["FolderID"] != null)
            {
                long folderID = 0;
                if (long.TryParse(Request["FolderID"], out folderID))
                {
                    fcSelectFolder.set(folderID);
                }
            }

        }

       
    }

    protected void grdUsers_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Contains("order"))
        {
            if (strOrder == e.CommandName.Substring(5))
            {
                strOrder = "";
                lstGridCourses = (from obj in lstGridCourses orderby obj.GetType().GetProperty(e.CommandName.Substring(5)).GetValue(obj, null) descending select obj).ToList();
            }
            else
            {
                strOrder = e.CommandName.Substring(5);
                lstGridCourses = (from obj in lstGridCourses orderby obj.GetType().GetProperty(e.CommandName.Substring(5)).GetValue(obj, null)  select obj).ToList();
            }


            grdUsers.DataSource = lstGridCourses;
            grdUsers.DataBind();

            
        }
    }



    /// <summary>
    /// this function will get if the language filter will shown or not
    /// </summary>
    private void showLanguage()
    {
        SystemOptionsDB objDB = new SystemOptionsDB(ConnectionStrings.LMS);
        List<SystemOptions> lst = objDB.Select("", "");
        if (lst.Count < 1)
        {
            dvShowLanguage.Visible = true;
            grdUsers.Columns[3].Visible = true;
        }
        else
        {

            dvShowLanguage.Visible = lst[0].ShowCourseLanguage;
            grdUsers.Columns[3].Visible = lst[0].ShowCourseLanguage;
        }


        if (lst.Count < 2)
        {
            
            grdUsers.Columns[2].Visible = true;
        }
        else
        {

            
            grdUsers.Columns[2].Visible = lst[1].ShowCourseLanguage;
        }


    }

    protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
    {
        //fcSelectFolder_SelectedItemChanged(sender, new CustomEventArgs(false,null));
        try
        {

            if (txtSearch.Text != "")
            {
                btnSearch_Click(sender, e);
                return;
            }

            if (fcSelectFolder.get() > 0)
            {
                BindGrid(new FoldersDB(ConnectionStrings.LMS).getFoldersByID(fcSelectFolder.get())[0]);

            }
            else
            {
                BindGrid(new Folders());
            }
        }
        catch
        {
        }
    }

    /// <summary>
    /// this function will bind the drop down list of languages
    /// </summary>
    private void bindddlLanguage()
    {
        LanguagesDB objDB = new LanguagesDB(ConnectionStrings.LMS);
        List<Languages> lst = objDB.Select("", "");
        lst = (from obj in lst orderby obj.LanguageNameEN select obj).ToList<Languages>();

        lst.Insert(0, new Languages { ID = -1, LanguageNameAR = "-- الكل --", LanguageNameEN = "-- All --" });

        ddlLanguage.DataSource = lst;
        ddlLanguage.DataTextField = "LanguageNameAR";
        ddlLanguage.DataValueField = "ID";
        ddlLanguage.DataBind();
        ddlLanguage.SelectedValue = "-1";

    }


























    /// <summary>
    /// this function will bind the courses grid by folder
    /// </summary>
    /// <param name="objFolder">the folder to bind the grid with</param>
    protected void BindGrid(Folders objFolder)
    {
        CoursesDB objCoursesDB = new CoursesDB(ConnectionStrings.LMS);

        List<Courses> lstCourses = new List<Courses>();


        //if (objFolder.ID == -1)
        //{ 
        //    lstCourses = objCoursesDB.Select("", " where [FolderID] is null ");
        //}
        //else
        //{
        //    lstCourses = objCoursesDB.Select("", " where [FolderID] = '" + objFolder.ID.ToString() + "' ");
        //}

        lstCourses = objFolder.lstRecursiveCourses;

        if (ddlLanguage.SelectedValue != "-1")
        {
            long language = long.Parse(ddlLanguage.SelectedValue);
            lstCourses = (from obj in lstCourses where obj.LanguageID == language select obj).ToList<Courses>();
        }

        lstGridCourses = new List<Courses>(from obj in lstCourses orderby  obj.CourseNameAR select obj);

        grdUsers.DataSource = lstGridCourses;
        grdUsers.DataBind();


    }


    /// <summary>
    /// this function will bind the courses grid by folder
    /// </summary>
    /// <param name="objFolder">the folder to bind the grid with</param>
    protected void BindGrid()
    {
        CoursesDB objCoursesDB = new CoursesDB(ConnectionStrings.LMS);


        string strSearch = txtSearch.Text.Trim();

        string strWhere = "";

        if (!strSearch.Equals(String.Empty))
        {

            strSearch = "'%" + strSearch.Replace("'", "''") + "%'";


            strWhere = " where [CourseNameAR] LIKE " + strSearch + " OR [CourseNameEN] LIKE " + strSearch
                + " OR [ObjectivesAR] LIKE " + strSearch + " OR [ObjectivesEN] LIKE " + strSearch
                + " OR [OutlineAR] LIKE " + strSearch + " OR [OutlineEN] LIKE " + strSearch
                + " OR [TargetAR] LIKE " + strSearch + " OR [TargetEN] LIKE " + strSearch + " ";


          

           
        }
        else
        {
            strWhere = "";
        }

        List<Courses> lstCourses = objCoursesDB.Select("", strWhere);



        //if (objFolder.ID == -1)
        //{ 
        //    lstCourses = objCoursesDB.Select("", " where [FolderID] is null ");
        //}
        //else
        //{
        //    lstCourses = objCoursesDB.Select("", " where [FolderID] = '" + objFolder.ID.ToString() + "' ");
        //}


        if (ddlLanguage.SelectedValue != "-1")
        {
            long language = long.Parse(ddlLanguage.SelectedValue);
            lstCourses = (from obj in lstCourses where obj.LanguageID == language select obj).ToList<Courses>();
        }


        lstGridCourses = lstGridCourses = new List<Courses>(from obj in lstCourses orderby  obj.CourseNameAR select obj);

        grdUsers.DataSource = lstGridCourses;
        grdUsers.DataBind();


    }

   


   


    /// <summary>
    /// this will handle the selection change in the selected folder control
    /// </summary>
    /// <param name="sender">the object sended this event</param>
    /// <param name="e">the params that contains the selected item</param>
    protected void fcSelectFolder_SelectedItemChanged(object sender, CustomEventArgs e)
    {
        
        Folders i_objFolder = (Folders)e.objArgs;


        if (i_objFolder != null)
        {

            BindGrid(i_objFolder);

        }
        else
        {
            BindGrid(new Folders());
        }
    }











   

    protected void grdUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdUsers.DataSource = lstGridCourses;
        grdUsers.PageIndex = e.NewPageIndex;

        grdUsers.DataBind();
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        BindGrid();

    }
    protected void grdUsers_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {


            Persons currentPerson = GlobalVars.getCurrentPersonAR();
            Courses cor = new Courses ();
            cor = (Courses)e.Row.DataItem;

            Panel pnl = (Panel)e.Row.FindControl("registerPanel");


            if (currentPerson.lstCourses.Contains(cor))
            {
                HyperLink hlEnrolled = new HyperLink();

                hlEnrolled.Text = "بدء الدورة";

                hlEnrolled.Target = "_Blank";

              
                    hlEnrolled.NavigateUrl = "start_learn_frame.aspx?id=" + cor.ID.ToString();
                


                

                pnl.Controls.Add(hlEnrolled);

                Literal ltNewLine = new Literal();
                ltNewLine.Text = "<br />";
                pnl.Controls.Add(ltNewLine);

                HyperLink hl = new HyperLink();
                hl.Text = "معلومات الدورة";
                hl.NavigateUrl = "./RegisterCourseAR.aspx?ID=" + cor.ID;
                hl.ToolTip = "View course details";

                pnl.Controls.Add(hl);

            }
            else
            {
                HyperLink hl = new HyperLink();
                hl.Text = "تسجيل";
                hl.NavigateUrl = "./RegisterCourseAR.aspx?ID=" + cor.ID;
                hl.ToolTip = "Enroll in this course";
                pnl.Controls.Add(hl);

                Literal ltNewLine = new Literal();
                ltNewLine.Text = "<br />";
                pnl.Controls.Add(ltNewLine);


                HyperLink hl1 = new HyperLink();
                hl1.Text = "معلومات الدورة";
                hl1.NavigateUrl = "./RegisterCourseAR.aspx?ID=" + cor.ID;
                hl1.ToolTip = "View course details";

                pnl.Controls.Add(hl1);
            }


            
        }
        

    }


    
}
